// pages/chat/worker.js

// 确保在生产环境中不会暴露API密钥，这里仅作示例
const API_KEY = '<DDC9wcHoDPzQgwypUwCHCuOfieNs9B1e>'; // 请替换为你的实际API密钥

self.onmessage = function(e) {
    const inputText = e.data;

    fetch('https://api.lkeap.cloud.tencent.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${API_KEY}`,  // 使用变量来存储API密钥
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            model: "deepseek-v3",
            messages: [{role: "user", content: inputText}]
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        // 增加数据验证以确保返回的数据结构符合预期
        if (data.choices && data.choices[0].message) {
            self.postMessage(data.choices[0].message.content);
        } else {
            throw new Error('Unexpected response structure');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        // 提供更具体的错误信息给前端
        self.postMessage(`Error: ${error.message || 'Unable to process your request.'}`);
    });
};